package com.zhuozhou.jdyc.main.main.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.NotificationManagerCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.zhuozhou.jdyc.R;
import com.zhuozhou.jdyc.api.ConstantsHelper;
import com.zhuozhou.jdyc.base.BaseActivity;
import com.zhuozhou.jdyc.databinding.ActivityMainBinding;
import com.zhuozhou.jdyc.main.main.fragment.BarterFragment;
import com.zhuozhou.jdyc.main.main.fragment.CartFragment;
import com.zhuozhou.jdyc.main.main.fragment.IndexFragment;
import com.zhuozhou.jdyc.main.main.fragment.IntegralFragment;
import com.zhuozhou.jdyc.main.main.fragment.MeFragment;
import com.zhuozhou.jdyc.main.main.viewmodel.MainViewModel;
import com.zhuozhou.jdyc.wight.customlayout.NavigationButton;
import com.zhuozhou.jdyc.wight.dialog.ConfirmDialog;

import java.util.Calendar;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class MainActivity extends BaseActivity<MainViewModel, ActivityMainBinding> {

    private FragmentManager mFragmentManager;
    public NavigationButton mCurrentNavButton;

    public static boolean isForeground = false;

    // 定义一个变量，来标识是否退出
    private static boolean isExit = false;

    // 所需的全部权限
    static String[] PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.ACCESS_FINE_LOCATION
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected boolean hasToolBar() {
        return false;
    }

    @Override
    public String setTitleBar() {
        return null;
    }


    //权限检测
    @NeedsPermission({Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_FINE_LOCATION})
    void checkPermission() {
        if (lacksPermissions(PERMISSIONS)) {
            requestPermission(ConstantsHelper.REQUEST_CODE, PERMISSIONS);
        }
        if (!NotificationManagerCompat.from(this).areNotificationsEnabled()) {
            new ConfirmDialog(this)
                    .setMessage("通知权限已关闭，是否前往设置中心开启此功能？")
                    .setCanOutSide(false)
                    .setSureText("前往开启")
                    .setOnSureClickListener(dialog -> {
                        try {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                Intent intent = new Intent();
                                intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
                                intent.putExtra(Settings.EXTRA_APP_PACKAGE, this.getPackageName());
                                intent.putExtra(Settings.EXTRA_CHANNEL_ID, this.getApplicationInfo().uid);
                                startActivity(intent);
                            } else {
                                Intent intent = new Intent();// 进入设置系统应用权限界面
                                intent.setAction("android.intent.action.MAIN");
                                intent.setClassName("com.android.settings", "com.android.settings.ManageApplications");
                                intent.setData(Uri.fromParts("package", this.getPackageName(), null));
                                startActivity(intent);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    })
                    .builder()
                    .show();
        }
    }

    @Override
    protected void onResume() {
        //收起键盘
        try {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) {
                imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(),
                        0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        isForeground = true;
        super.onResume();
    }

    @Override
    protected void onPause() {
        //收起键盘
        try {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) {
                imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(),
                        0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        isForeground = false;
        super.onPause();
    }

    /**
     * show the MainActivity
     *
     * @param context context
     */
    public static void show(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }

    //初始化布局
    @Override
    public void initView() {
//        if (lacksPermissions(PERMISSIONS)) {This project contains Java compilation errors, which can cause rendering failures for custom views. Fix compilation problems first.
//            requestPermission(ConstantsHelper.REQUEST_CODE, PERMISSIONS);
//        }
        binding.nvIndex.init(R.drawable.main_index_selector, R.string.nv_index, IndexFragment.class);
        binding.nvIntegral.init(R.drawable.main_setting_selector, R.string.nv_integral, IntegralFragment.class);
        binding.nvBarter.init(R.drawable.main_man_selector, R.string.nv_barter, BarterFragment.class);
        binding.nvCart.init(R.drawable.main_cart_selector, R.string.nv_cart, CartFragment.class);
        binding.nvMe.init(R.drawable.main_me_selector, R.string.nv_me, MeFragment.class);
        if (baseBundle.getInt("openType", 1) == 4) {
            mCurrentNavButton = binding.nvCart;
            binding.nvCart.setSelected(true);
            doTabChanged(null, binding.nvCart);
        } else if (baseBundle.getInt("openType", 1) == 3) {
            mCurrentNavButton = binding.nvBarter;
            binding.nvBarter.setSelected(true);
            doTabChanged(null, binding.nvBarter);
        } else if (baseBundle.getInt("openType", 1) == 2) {
            mCurrentNavButton = binding.nvIntegral;
            binding.nvIntegral.setSelected(true);
            doTabChanged(null, binding.nvIntegral);
        } else {
            mCurrentNavButton = binding.nvIndex;
            binding.nvIndex.setSelected(true);
            doTabChanged(null, binding.nvIndex);
        }
        checkPermission();

    }

    @Override
    public void initData(Bundle bundle) {

    }

    private long lastClickTime = 0;

    public void onClick(View v) {
        long currentTime = Calendar.getInstance().getTimeInMillis();
        if (currentTime - lastClickTime < 300) {
            lastClickTime = currentTime;
            return;
        }
        lastClickTime = currentTime;
        if (v instanceof NavigationButton) {
            NavigationButton nav = (NavigationButton) v;
            doSelect(nav);
        }
    }

    public void doSelect(NavigationButton newNavButton) {
        NavigationButton oldNavButton = null;
        if (mCurrentNavButton != null) {
            oldNavButton = mCurrentNavButton;
            oldNavButton.setSelected(false);
        }
        newNavButton.setSelected(true);
        doTabChanged(oldNavButton, newNavButton);
        mCurrentNavButton = newNavButton;
    }

    private void doTabChanged(NavigationButton oldNavButton, NavigationButton newNavButton) {
        mFragmentManager = getSupportFragmentManager();
        FragmentTransaction ft = mFragmentManager.beginTransaction();
        if (oldNavButton != null) {
            if (oldNavButton.getFragment() != null) {
                ft.detach(oldNavButton.getFragment());
            }
        }
        if (newNavButton != null) {
            if (newNavButton.getFragment() == null) {
                Fragment fragment = Fragment.instantiate(MainActivity.this,
                        newNavButton.getClx().getName(), null);
                ft.add(R.id.frameLayout, fragment, newNavButton.getTag());
                newNavButton.setFragment(fragment);
            } else {
                ft.attach(newNavButton.getFragment());
            }
        }
        ft.commit();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 主线程处理视图，isExit默认为false，就是点击第一次时，弹出"再按一次退出程序"
     * 点击第二次时关闭应用
     */
    Handler mHandler = new Handler(message -> {
        isExit = false;
        return false;
    });

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 点击两次退出程序
     */
    private void exit() {
        if (!isExit) {
            isExit = true;
            Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            // 利用handler延迟发送更改状态信息
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            finish();
            //参数用作状态码；根据惯例，非 0 的状态码表示异常终止。
            System.exit(0);
        }
    }

    //    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == ConstantsHelper.REQUEST_CODE && resultCode == PermissionsActivity.PERMISSIONS_DENIED) {
//            new ConfirmDialog(this)
//                    .setMessage("缺少关键权限,部分功能无法正常使用")
//                    .setCanOutSide(false)
//                    .setSureText("授权")
//                    .setOnSureClickListener(dialog -> {
//                        requestPermission(ConstantsHelper.REQUEST_CODE, PERMISSIONS);
//                    })
//                    .builder().show();
//        }
//    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (null != this.getCurrentFocus()) {
            /*
             * 点击空白位置 隐藏软键盘
             */
            InputMethodManager mInputMethodManager = (InputMethodManager) this.getSystemService(INPUT_METHOD_SERVICE);
            return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
        return super.onTouchEvent(event);
    }

}
